package cn.nexd.map.rendering.core.helper;

import android.text.TextUtils;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import cn.nexd.map.rendering.core.componet.data.Floors;

/**
 * Created by codingfish on 15/8/13.
 */
public class FloorsUtils {

    private FloorsUtils() {
    }

    public static FloorsUtils getFloorsUtils() {
        return FloorsUtilsInstance.FLOORS_UTILS;
    }

    Map<Long, String> map;

    public Floors getFloors(InputStream inputStream) {

        final Floors floors = new Floors();

        SAXParserFactory factory = SAXParserFactory.newInstance();
        try {
            SAXParser parser = factory.newSAXParser();
            XMLReader reader = parser.getXMLReader();

            reader.setContentHandler(new DefaultHandler() {
                @Override
                public void startDocument() throws SAXException {
                }

                @Override
                public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                    map = new HashMap<Long, String>();
                    if (TextUtils.equals("mall", localName)) {
                        floors.setId(Long.parseLong(attributes.getValue("id")));
                        floors.setName(attributes.getValue("name"));
                        floors.setFloorCount(Integer.parseInt(attributes.getValue("floorcount")));

                    } else if (TextUtils.equals("floor", localName)) {
                        map.put(Long.parseLong(attributes.getValue("id")), attributes.getValue("string"));
                    }
                }

                @Override
                public void endElement(String uri, String localName, String qName) throws SAXException {
                    if (TextUtils.equals("mall", localName)) {
                        floors.setFloors(map);
                    }
                }

                @Override
                public void endDocument() throws SAXException {
                }
            });

            reader.parse(new InputSource(inputStream));

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return floors;
    }

    private static class FloorsUtilsInstance {
        public static final FloorsUtils FLOORS_UTILS = new FloorsUtils();
    }

}
